package com.kanq.aspect;

import com.kanq.config.DecryptProperties;
import com.kanq.util.SM4Util;
import jakarta.annotation.Resource;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@Aspect
@Component
public class DecryptAspect {

    @Value("${decrypt.enabled:false}")
    private boolean decryptEnabled;

    @Value("${decrypt.local.enabled:false}")
    private boolean localDecryptEnabled;

    @Value("${decrypt.local.sm4-key}")
    private String sm4Key;

    @Resource
    private DecryptProperties decryptProperties;

    @Resource
    private RestTemplate restTemplate;

    @Around("execution(* com.kanq.controller.EncryptController.*(..))")
    public Object decryptRequest(ProceedingJoinPoint joinPoint) throws Throwable {
        if (!decryptEnabled) {
            return joinPoint.proceed();
        }

        try {
            // 获取原始参数
            Object[] args = joinPoint.getArgs();

            // 遍历参数，查找需要解密的参数
            String encryptedData = null;
            for (Object arg : args) {
                if (arg instanceof String && ((String) arg).startsWith("ENC:")) {
                    encryptedData = ((String) arg).substring(4);
                    break;
                }
            }

            if (encryptedData == null) {
                return joinPoint.proceed();
            }

            String decryptedData;
            if (localDecryptEnabled) {
                // 本地SM4解密
                decryptedData = decryptBySM4(encryptedData);
            } else {
                // 调用第三方解密接口
                Map<String, String> request = new HashMap<>();
                request.put("user", encryptedData);

                decryptedData = restTemplate.postForObject(
                        decryptProperties.getUrl(),
                        request,
                        String.class);
            }

            // 替换解密后的参数 - 找到原始加密参数的位置
            for (int i = 0; i < args.length; i++) {
                if (args[i] instanceof String && ((String) args[i]).startsWith("ENC:")) {
                    args[i] = decryptedData;
                    break;
                }
            }

            return joinPoint.proceed(args);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("解密失败: " + e.getMessage());
        }
    }

    /**
     * SM4解密方法
     */
    private String decryptBySM4(String encryptedData) throws Exception {
        return SM4Util.decrypt(encryptedData, sm4Key);
    }
}